package top.xiaoazi.futureletterserver.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置key value 默认以
     * @param key
     * @param value
     */
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }


    /**
     * 设置key并设置过期时间，时间单位默认是分钟
     * @param key
     * @param value
     * @param seconds
     */
    public void set(String key, Object value, long seconds) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
    }

    /**
     * 设置 value 并自定义过期时常和过期的单位
     * @param key
     * @param value
     * @param outTime
     * @param timeUnit
     */
    public void set(String key, Object value, long outTime, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, outTime, timeUnit);
    }

    /**
     * 获取 key 对应的 value
     * @param key
     * @return
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取 key 返回 value 的 toString
     * @param key
     * @return
     */
    public String getString(String key) {
        Object obj = redisTemplate.opsForValue().get(key);
        return obj == null ? null : obj.toString();
    }

    /**
     * 删除某个键
     * @param key
     * @return
     */
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 是否存在键
     * @param key
     * @return
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
}
